package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import io.xxx.xbutler.data.TagMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取机器人的标签列表回调
 *
 * <pre>
 * {
 *     "nType": 2001,
 *     "vcMerchantNo": "",
 *     "vcRobotWxId": "",
 *     "vcRobotSerialNo": "",
 *     "vcSerialNo": "",
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "Data": [
 *         {
 *             "nTagId": 1,
 *             "vcTagName": "",
 *             "vcBase64TagName": ""
 *         }
 *     ]
 * }
 * </pre>
 */
@Slf4j
@Component
public class _2001Handler implements CallbackHandler {

    @Resource
    private TagMapper tagMapper;

    @Override
    public String name() {
        return "获取机器人的标签列表回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 2001;
    }

    @Override
    public void handle(Callback callback) {
        LocalDateTime now = LocalDateTime.now();
        JSONArray data = (JSONArray) callback.getData();
        List<Tag> tags = data.stream()
                .map(it -> {
                    JSONObject info = JSONObject.from(it);
                    return new Tag()
                            .setContactId(callback.getRobotId())
                            .setContactSerialNo(callback.getRobotSerialNo())
                            .setId(info.getLong("nTagId"))
                            .setName(info.getString("vcTagName"))
                            .setBase64Name(info.getString("vcBase64TagName"))
                            .setCreatedTime(now);
                })
                .toList();
        List<Long> tagIds = tags.stream()
                .map(Tag::getId)
                .toList();
        List<Tag> oldTags = tagMapper.selectByIds(tagIds);
        List<Tag> allTags = new ArrayList<>(tags);
        allTags.removeAll(oldTags);
        tagMapper.insertOrUpdate(allTags);
    }
}
